package cn.turboinfo.fuyang.api.domain.web.usecase.file;

import cn.turboinfo.fuyang.api.domain.common.service.file.FileAttachmentService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.domain.web.component.file.FileAttachmentHelper;
import cn.turboinfo.fuyang.api.entity.common.pojo.file.FileAttachment;
import cn.turboinfo.fuyang.api.entity.common.pojo.file.TinymceFileAttachment;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * 上传附件
 *
 * @author sunshow
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UploadTinymceFileAttachmentUseCase extends AbstractUseCase<UploadTinymceFileAttachmentUseCase.InputData, UploadTinymceFileAttachmentUseCase.OutputData> {

    private final FileAttachmentHelper fileAttachmentHelper;

    private final FileAttachmentService fileAttachmentService;

    @SneakyThrows
    @Override
    protected OutputData doAction(InputData inputData) {
        // 保存上传的附件
        FileAttachment fileAttachment = fileAttachmentService.assembleExternalUrl(
                fileAttachmentHelper.checkAndSaveFileAttachment(
                        inputData.getFile(),
                        inputData.getAllowExts(),
                        inputData.getRelativePath(),
                        inputData.getRefType(),
                        inputData.getRefId(),
                        false)
        );

        log.info("上传文件已保存, displayName={}, filename={}, relativePath={}", fileAttachment.getDisplayName(), fileAttachment.getFilename(), fileAttachment.getRelativePath());

        TinymceFileAttachment tinymceFileAttachment = new TinymceFileAttachment();
        tinymceFileAttachment.setLocation(fileAttachment.getExternalUrl());
        tinymceFileAttachment.setId(fileAttachment.getId());

        return OutputData.builder()
                .attachment(tinymceFileAttachment)
                .build();
    }

    @Getter
    @Setter
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(message = "文件不能为空")
        private MultipartFile file;

        @NotEmpty(message = "允许的文件类型不能为空")
        private String[] allowExts;

        @NotEmpty(message = "保存路径不能为空")
        private String relativePath;

        @NotEmpty(message = "关联业务类型不能为空")
        private String refType;

        private Long refId;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private TinymceFileAttachment attachment;


    }
}
